<template>
    <div style="overflow: hidden;height: 50px;">
        <div :style="{'height': height}" :class="{'scroll-tab': !noScroll, 'no-scroll': noScroll}" ref="scrollTab">
            <slot></slot>
            <div ref="tabBar" style="height: 2px;background: #075ebb;position: absolute;bottom: 5px;" class="tabBar">
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'scrollTab',
    data() {
        return {
            index: -1
        };
    },
    props: {
        height: { //设置高度 默认55px
            type: String,
            default: '55px'
        },
        goIndex: { //指定跳转tab
            type: Number,
            default: -1
        },
        noScroll: { //时候出现滚动模式
            type: Boolean,
            default: false
        }
    },
    methods: {
        /*
        * 获取tabitem传回的id
        * */
        isIndexOf(index) {
            this.index = index;
        },
        /*
        * 给tabItem组件绑定id
        * */
        updateIndex() {
            if (!this.$children || !this.$children.length) return;
            this.number = this.$children.length;
            let children = this.$children;
            for (let i = 0; i < children.length; i++) {
                children[i].currentIndex = i;
            }
        }
    },
    watch: {
        index(val, oldValue) {
            if (oldValue >= 0) {
                this.$children[oldValue].$el.style.color = '#999';
                this.$children[oldValue].$el.className = this.$children[val].$el.className.split(' ')[0];
            }
            this.$refs.tabBar.style.left = `${this.$children[val].$el.offsetLeft}px`;
            this.$refs.tabBar.style.width = `${this.$children[val].$el.clientWidth}px`;
            this.$refs.scrollTab.scrollLeft = this.$children[val].$el.offsetLeft;
            this.$children[val].$el.style.color = '#075ebb';
            this.$children[val].$el.className += ' cur';
        },
        goIndex(val) {
            this.index = val;
        }
    },
    mounted() {
        /*初始化调用*/
        this.updateIndex();
        /*无滚动条模式下获取第一个导航的宽度*/
        this.$nextTick(() => {
            if (this.$children[0]) {
                this.$refs.tabBar.style.width = this.$children[0].$el.clientWidth + 'px';
            }
        });
    }
};
</script>

<style scoped>
.no-scroll{
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    position: relative;
    background: #ffffff;
}
.scroll-tab{
    width: 100%;
    overflow-x: auto;
    white-space:nowrap;
    position: relative;
    background: #ffffff;
    overflow-y: hidden;
}
.tabBar{
    transition: right 0.3s cubic-bezier(0.35, 0, 0.25, 1) 0.09s, left 0.3s cubic-bezier(0.35, 0, 0.25, 1);
}
</style>
